import React, { useState, useEffect } from 'react'
import apiService from '../utils/api.js'
import PlaylistForm from './PlaylistForm.jsx'

const PlaylistsManagement = () => {
  // 歌单管理相关状态
  const [playlists, setPlaylists] = useState([])
  const [isAddingPlaylist, setIsAddingPlaylist] = useState(false)
  const [isEditingPlaylist, setIsEditingPlaylist] = useState(false)
  const [showOfficialOption, setShowOfficialOption] = useState(false)
  const [currentPlaylist, setCurrentPlaylist] = useState(null)
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(true)
  const [showPlaylistDetail, setShowPlaylistDetail] = useState(false)
  const [selectedPlaylist, setSelectedPlaylist] = useState(null)
  const [playlistSongs, setPlaylistSongs] = useState([])

  // 获取歌单列表
  const fetchPlaylists = async () => {
    try {
      setLoading(true)
      //获取登录人ID
      const currentUser = apiService.getCurrentUser()
      setShowOfficialOption(currentUser?.isAdmin)
      const response = await apiService.getRecommendedPlaylistsForAdmin()
      if (response.code === 200 && response.data) {
        setPlaylists(response.data)
      } else {
        // 如果API调不通，使用模拟数据
        setPlaylists([
          { id: 1, name: '热门歌单', description: '热门流行歌曲集合', coverImageUrl: 'https://via.placeholder.com/300?text=Playlist1' },
          { id: 2, name: '古典音乐精选', description: '古典音乐经典作品', coverImageUrl: 'https://via.placeholder.com/300?text=Playlist2' },
          { id: 3, name: '摇滚盛宴', description: '震撼摇滚歌曲合集', coverImageUrl: 'https://via.placeholder.com/300?text=Playlist3' }
        ])
      }
    } catch (error) {
      console.error('获取歌单列表失败:', error)
      setError('获取歌单列表失败')
      // 使用模拟数据
      setPlaylists([
        { id: 1, name: '热门歌单', description: '热门流行歌曲集合', coverImageUrl: 'https://via.placeholder.com/300?text=Playlist1' },
        { id: 2, name: '古典音乐精选', description: '古典音乐经典作品', coverImageUrl: 'https://via.placeholder.com/300?text=Playlist2' },
        { id: 3, name: '摇滚盛宴', description: '震撼摇滚歌曲合集', coverImageUrl: 'https://via.placeholder.com/300?text=Playlist3' }
      ])
    } finally {
      setLoading(false)
    }
  }

  // 获取歌单详情（包含歌曲列表）
  const fetchPlaylistDetail = async (playlistId) => {
    try {
      setLoading(true)
      // 实际项目中应该有专门的获取歌单详情的API
      // 这里使用模拟数据
      const mockSongs = [
      ]
      const response = await apiService.getPlaylistDetail(playlistId)
      if (response.code === 200 && response.data) {
        setPlaylistSongs(response.data.songs || [])
      } else {
        setPlaylistSongs(mockSongs)
      }
    } catch (error) {
      console.error('获取歌单详情失败:', error)
      setError('获取歌单详情失败')
    } finally {
      setLoading(false)
    }
  }

  // 组件首次加载时获取歌单列表
  useEffect(() => {
    fetchPlaylists()
  }, [])

  // 准备添加歌单
  const prepareAddPlaylist = () => {
    setCurrentPlaylist(null)
    setIsAddingPlaylist(true)
    setIsEditingPlaylist(false)
  }

  // 准备编辑歌单
  const prepareEditPlaylist = (playlist) => {
    setCurrentPlaylist(playlist)
    setIsAddingPlaylist(false)
    setIsEditingPlaylist(true)
  }

  // 取消添加/编辑歌单
  const cancelPlaylistAction = () => {
    setIsAddingPlaylist(false)
    setIsEditingPlaylist(false)
    setCurrentPlaylist(null)
  }

  // 处理删除歌单
  const handleDeletePlaylist = async (playlistId) => {
    if (window.confirm('确定要删除这个歌单吗？')) {
      try {
        await apiService.deletePlaylist(playlistId)
        fetchPlaylists()
      } catch (error) {
        console.error('删除歌单失败:', error)
        setError('删除歌单失败，请重试')
      }
    }
  }

  // 查看歌单详情
  const viewPlaylistDetail = (playlist) => {
    setSelectedPlaylist(playlist)
    setShowPlaylistDetail(true)
    fetchPlaylistDetail(playlist.id)
  }

  // 关闭歌单详情
  const closePlaylistDetail = () => {
    setShowPlaylistDetail(false)
    setSelectedPlaylist(null)
    setPlaylistSongs([])
  }

  // 处理歌单表单提交
  const handlePlaylistFormSubmit = async (formData) => {
    try {
      if (isEditingPlaylist && currentPlaylist) {
        await apiService.updatePlaylist(currentPlaylist.id, formData)
      } else {
        await apiService.createPlaylist(formData)
      }
      cancelPlaylistAction()
      fetchPlaylists()
    } catch (error) {
      console.error('保存歌单失败:', error)
      setError('保存歌单失败，请重试')
    }
  }

  // 处理移除歌曲
  const handleRemoveSong = async (songId) => {
    if (window.confirm('确定要从歌单中移除这首歌吗？')) {
      try {
        await apiService.removeSongFromPlaylist({
          playlistId: selectedPlaylist.id,
          songId
        })
        fetchPlaylistDetail(selectedPlaylist.id)
      } catch (error) {
        console.error('移除歌曲失败:', error)
        setError('移除歌曲失败，请重试')
      }
    }
  }

  return (
    <>
      <div className="section-header">
        <button className="btn-add" onClick={prepareAddPlaylist}>
          添加歌单
        </button>
      </div>

      {error && (
        <div className="error-message">
          {error}
          <button onClick={() => setError('')}>×</button>
        </div>
      )}

      {loading && !showPlaylistDetail ? (
        <div className="loading">加载中...</div>
      ) : (
        <div className="songs-table-container">
          <table className="songs-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>封面</th>
                <th>歌单名称</th>
                <th>描述</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {playlists.map(playlist => (
                <tr key={playlist.id}>
                  <td>{playlist.id}</td>
                  <td>
                    <img 
                      src={playlist.coverImageUrl} 
                      alt={playlist.name} 
                      className="song-cover-small"
                    />
                  </td>
                  <td>{playlist.name}</td>
                  <td>{playlist.description || '-'}</td>
                  <td>
                    <button 
                      className="btn-view"
                      onClick={() => viewPlaylistDetail(playlist)}
                    >
                      查看
                    </button>
                    <button 
                      className="btn-edit"
                      onClick={() => prepareEditPlaylist(playlist)}
                    >
                      编辑
                    </button>
                    <button 
                      className="btn-delete"
                      onClick={() => handleDeletePlaylist(playlist.id)}
                    >
                      删除
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* 歌单详情模态框 */}
      {showPlaylistDetail && selectedPlaylist && (
        <div className="song-form-modal">
          <div className="song-form">
            <div className="modal-header">
              <h3>歌单详情：{selectedPlaylist.name}</h3>
              <button className="close-btn" onClick={closePlaylistDetail}>×</button>
            </div>
            <div className="playlist-detail">
              <img 
                src={selectedPlaylist.coverImageUrl} 
                alt={selectedPlaylist.name} 
                className="playlist-cover-large"
              />
              <div className="playlist-info">
                <h4>{selectedPlaylist.name}</h4>
                <p>{selectedPlaylist.description || '暂无描述'}</p>
              </div>
              
              <div className="playlist-songs-section">
                <h4>歌曲列表</h4>
                <div className="playlist-songs-list">
                  {loading ? (
                    <div className="loading">加载中...</div>
                  ) : playlistSongs.length > 0 ? (
                    playlistSongs.map(song => (
                      <div key={song.id} className="playlist-song-item">
                        <div className="playlist-song-info">
                          <p className="playlist-song-title">{song.title}</p>
                          <p className="playlist-song-artist">{song.artist ? song.artist.name : '-'} - {song.album ? song.album.title : '-'}</p>
                          <p className="playlist-song-artist">
                            <button className="btn-remove" onClick={() => handleRemoveSong(song.id)}>移除</button>
                          </p>
                          
                        </div>
                      </div>
                    ))
                  ) : (
                    <div className="empty-state">暂无歌曲</div>
                  )}
                </div>
              </div>
            </div>
            <div className="form-actions">
              <button type="button" onClick={closePlaylistDetail}>关闭</button>
            </div>
          </div>
        </div>
      )}
      
      {/* 添加/编辑歌单表单（使用可复用组件） */}
      <PlaylistForm
        isVisible={isAddingPlaylist || isEditingPlaylist}
        isEditing={isEditingPlaylist}
        initialData={currentPlaylist}
        showOfficialOption={true}
        onSubmit={handlePlaylistFormSubmit}
        onCancel={cancelPlaylistAction}
      />
    </>
  )
}

export default PlaylistsManagement